package com.maserb.monitor.remote;

import com.maserb.monitor.dataCenter.communication.MonitorMessageProtocol;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;
import io.netty.util.ReferenceCountUtil;

import java.util.concurrent.TimeUnit;

public class AFSTClientHandler extends ChannelInboundHandlerAdapter {

    private AFSTClient client;

    public AFSTClientHandler(AFSTClient client) {
        this.client = client;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        int index = 0;
        while (true) {
            SchoolRecordRequestEntity record = new SchoolRecordRequestEntity();
            record.setDeviceId("1");
            record.setCardId("2");
            record.setStudentId("" + index);
            record.setStartTime("20170319101122");

            byte[] data = record.getBytes();
            AFSTMessageProtocol protocol = new AFSTMessageProtocol(data.length, "01", 1, data);
            ctx.writeAndFlush(protocol);

            Thread.sleep(1000);
            index += 1;
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            // 用于获取服务端发来的数据信息
            AFSTMessageProtocol body = (AFSTMessageProtocol) msg;
            System.out.println("Client接受的服务端的信息 :" + body.toString());

        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        final EventLoop eventLoop = ctx.channel().eventLoop();
        eventLoop.schedule(new Runnable() {
            @Override
            public void run() {
                client.createBootstrap(new Bootstrap(), eventLoop);
            }
        }, 1L, TimeUnit.SECONDS);
        super.channelInactive(ctx);
    }
}
